package com.guoqi.oabridge

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.AbsoluteLayout
import android.widget.ProgressBar
import com.tencent.smtt.export.external.interfaces.JsPromptResult
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView


/**
 *  作者    GUOQI
 *  时间    2019/2/12 13:44
 *  描述
 */
class X5WebView : WebView {
    companion object {
        val TAG = "X5WebView"
        val UA =
            "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.360123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199";
    }

    private var progressbar: ProgressBar? = null
    private var listener: TitleListener? = null

    constructor(arg0: Context) : super(arg0) {
        setBackgroundColor(85621)
    }

    constructor(arg0: Context, arg1: AttributeSet) : super(arg0, arg1) {
        setWebViewClient(WebViewClient())
        setWebChromeClient(WebChromeClient());
        initWebViewSettings()
    }

    private fun initProgressBar(id: Int) {
        progressbar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal)
        progressbar!!.layoutParams = AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, 5, 0, 0)
        progressbar!!.progressDrawable = context.resources.getDrawable(id)
        addView(progressbar)

    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebViewSettings() {
        settings.apply {
            userAgentString = UA
            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            allowFileAccess = true
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            setSupportZoom(true)
            builtInZoomControls = true
            displayZoomControls = false
            textZoom = 100                  //防止大字体模式改变表格
            useWideViewPort = true          //true内容宽度沾满屏幕  false超出屏幕放大显示局部
            setSupportMultipleWindows(true)
            loadWithOverviewMode = true
            setAppCacheEnabled(true)
            databaseEnabled = true
            domStorageEnabled = true
            setGeolocationEnabled(true)
            setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
            pluginState = WebSettings.PluginState.ON_DEMAND
            setRenderPriority(WebSettings.RenderPriority.HIGH)
            saveFormData = true
            //settingsExtension.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY)
            cacheMode = WebSettings.LOAD_DEFAULT
        }
        setOnLongClickListener { true }
    }

    inner class WebViewClient : com.tencent.smtt.sdk.WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
            view.loadUrl(url)
            return true
        }
    }

    inner class WebChromeClient : com.tencent.smtt.sdk.WebChromeClient() {
        override fun onProgressChanged(p0: WebView?, p1: Int) {
            progressbar?.let {
                if (p1 == 100) {
                    it.visibility = View.GONE
                } else {
                    if (it.visibility == View.GONE) {
                        it.visibility = View.VISIBLE
                    }
                    it.progress = p1
                }
            }
            super.onProgressChanged(p0, p1)
        }

        override fun onReceivedTitle(p0: WebView?, title: String?) {
            super.onReceivedTitle(p0, title)
            if (title != null) {
                listener?.getTitle(title)
            }
        }

        override fun onJsAlert(p0: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            result?.confirm()
            return true
        }

        override fun onJsConfirm(p0: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            result?.confirm()
            return true
        }

        override fun onJsPrompt(
            p0: WebView?,
            url: String?,
            message: String?,
            defaultValue: String?,
            result: JsPromptResult?
        ): Boolean {
            Log.e(TAG, message)
            result?.confirm(JSBridge.callJava(p0, message))
            return true
        }
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        progressbar?.let {
            val lp = it.layoutParams as AbsoluteLayout.LayoutParams
            lp.x = l
            lp.y = t
            it.layoutParams = lp
        }
        super.onScrollChanged(l, t, oldl, oldt)
    }

    interface TitleListener {
        fun getTitle(title: String)
    }

    fun setOnTitleListener(titleListener: TitleListener) {
        listener = titleListener
    }

    fun loadUrl(p0: String?, showProgressBar: Boolean, drawable: Int?) {
        if (showProgressBar) {
            initProgressBar(drawable ?: R.drawable.view_progress_webview)
        }
        super.loadUrl(p0)
    }
}